
angular.module('EmailApp')
.constant('localStorage', window.localStorage)
.factory('EmailService', function(localStorage) {
        var incomingEmails = [];
        var outgoingEmails = [];

        var exports = {};

        exports.getIncomingEmails = function() {
            incomingEmails = JSON.parse(localStorage.getItem("EmailApp.income"))
            return incomingEmails
        };

        exports.getOutgoingEmails = function() {
            outgoingEmails = JSON.parse(localStorage.getItem("EmailApp.outgoing"))
            return outgoingEmails;
        };

        exports.addOutgoingEmail = function(email){
            var m = email;
            m.date = now();
            outgoingEmails.push(m);
            localStorage.setItem("EmailApp.outgoing", JSON.stringify(outgoingEmails))
        }

        exports.addIncomingEmail = function(email) {
            var m = email;
            m.date = now();
            incomingEmails.push(m);
            localStorage.setItem("EmailApp.income", JSON.stringify(incomingEmails))
        };

        exports.updateIncomingEmail = function(email) {
            for(var i=0;i<incomingEmails.length;i++) {
                if(incomingEmails[i].timestamp == email.timestamp) {
                    incomingEmails[i] = email;
                    localStorage.setItem("EmailApp.income", JSON.stringify(incomingEmails))
                }
            }
        };

        function now(){
            var currentdate = new Date();
            //return currentdate.getDate() + "/"
            //    + (currentdate.getMonth()+1)  + "/"
            //    + currentdate.getFullYear() + "-"
            //    + currentdate.getHours() + ":"
            //    + currentdate.getMinutes() + ":"
            //    + currentdate.getSeconds();
            return currentdate.getTime();
        }

        return exports;

    })
